package org.whuims.pois.action;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.whuims.pois.action.result.ClusterVo;
import org.whuims.pois.dao.NewsDao;
import org.whuims.pois.dao.TopicDao;
import org.whuims.pois.hibernate.BaseDao;
import org.whuims.pois.model.Cluster;
import org.whuims.pois.model.TopicC;
import org.whuims.pois.report.Documents;
import org.whuims.pois.report.PeriodCluster;
import org.whuims.pois.report.chart2Pic.Chart2PNG;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by john on 2015/5/22.
 */
public class PDFAction extends DispatchAction {
    private NewsDao newsDao = new NewsDao();
    private BaseDao baseDao = new BaseDao();
    //    public static final String PATH = "F:/Test/";
    public static final String PATH = "/info/data/pdf_temp/";

    public ActionForward generatePDF(ActionMapping mapping, ActionForm form,
                                     HttpServletRequest request, HttpServletResponse response) {
        String startDate = request.getParameter("sd");
        String endDate = request.getParameter("ed");
        Timestamp start = null;
        Timestamp end = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if (startDate == null || startDate.trim().equals("")) {
                start = new Timestamp(new Date().getTime() - 30 * 24 * 60 * 60 * 1000);
            } else {
                start = new Timestamp(simpleDateFormat.parse(startDate).getTime());

            }
            if (endDate == null || endDate.trim().equals("")) {
                end = new Timestamp(new Date().getTime());
            } else {
                end = new Timestamp(simpleDateFormat.parse(endDate).getTime());
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
        TopicC topic = getTopic(request);   //主題
        if (topic == null) {
            return mapping.findForward("login");
        }
        try {
            String result = pdf(topic, start, end);
            System.out.println(result);
            //下载到哪里？客户端
            OutputStream os = response.getOutputStream();
            //弹出下载的框filename:提示用户下载的文件名
            response.addHeader("content-disposition", "attachment;filename=" + java.net.URLEncoder.encode(result, "utf-8"));
            InputStream is = new FileInputStream(result);
            byte[] b = new byte[1024];
            int size = is.read(b);
            while (size > 0) {
                os.write(b, 0, size);
                size = is.read(b);
            }
            is.close();
            os.close();
            return null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    private TopicC getTopic(HttpServletRequest request) {
        Object topic = request.getSession().getAttribute("topicId");
        if (topic == null) {
            return null;
        }
        return (TopicC) baseDao.getByPk(TopicC.class, (Long) topic);
    }


    public String pdf(TopicC topicC, Timestamp start, Timestamp end) throws FileNotFoundException, DocumentException {
        long first = new Date().getTime();
        Rectangle rectangle = new Rectangle(PageSize.A4);
        Document document = new Document(rectangle, 40, 40, 40, 40);
        //TODO 临时文件
        String file = PATH + getName(topicC, start, end);
        PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        document.add(Documents.title());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        String startStr = sdf.format(start);
        String endStr = sdf.format(end);
        document.add(Documents.info(topicC.getName(), startStr, endStr));
        int[] count = newsDao.statistic(topicC.getId(), startStr, endStr);
        document.add(Documents.basic_statistic(count[0], count[1], count[2], count[3], count[4], count[5]));
        java.util.List<ClusterVo> list = new ArrayList<>();
        //统计时间
        long time = new Date().getTime();
        System.out.println("基本信息统计耗时：" + (time - first) / 1000 + " s");
        first = time;

        list = new PeriodCluster().periodCluster(start, end, topicC.getId());

        time = new Date().getTime();
        System.out.println("聚类耗时：" + (time - first) / 1000 + " s");
        first = time;

        document.add(Documents.topic(list));
        List<File> siteTrends = Chart2PNG.newsSiteTrend(startStr, endStr, topicC.getId(), null, null);
        List<File> timeSerials = Chart2PNG.newsTimeTrend(startStr, endStr, topicC.getId(), null);

        time = new Date().getTime();
        System.out.println("绘图耗时：" + (time - first) / 1000 + " s");
        first = time;

        document.add(Documents.image("新闻", timeSerials.get(0).getAbsolutePath(), siteTrends.get(0).getAbsolutePath()));
        document.add(Documents.image("论坛", timeSerials.get(1).getAbsolutePath(), siteTrends.get(1).getAbsolutePath()));
        document.add(Documents.image("微博", timeSerials.get(2).getAbsolutePath(), siteTrends.get(2).getAbsolutePath()));
        document.add(Documents.image("博文", timeSerials.get(3).getAbsolutePath(), siteTrends.get(3).getAbsolutePath()));
        document.add(Documents.image("微信", timeSerials.get(4).getAbsolutePath(), siteTrends.get(4).getAbsolutePath()));
        for (int i = 0; i < timeSerials.size(); i++) {
            timeSerials.get(i).delete();
        }
        for (int i = 0; i < siteTrends.size(); i++) {
            siteTrends.get(i).delete();
        }
        document.add(Documents.foot());

        time = new Date().getTime();
        System.out.println("文档耗时：" + (time - first) / 1000 + " s");

        document.close();
        return file;
    }

    private String getName(TopicC topicC, Timestamp start, Timestamp end) {
        return topicC.getName() + "_" + start.getTime() + "_" + end.getTime() + "_" + new Random().nextInt(1000) + ".pdf";
    }
}
